import React, { useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';

const LoginPage: React.FC = () => {
  const history = useHistory();
  const location = useLocation();

  useEffect(() => {
    // 检查是否已登录
    const token = localStorage.getItem('token');
    if (token) {
      console.log('User already logged in, redirecting to /profile');
      history.push('/profile');
      return;
    }
  }, [history]);

  const handleLogin = async () => {
    try {
      // 发送登录请求到后端
      const res = await fetch('http://localhost:3379/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (!res.ok) {
        throw new Error('Login failed');
      }

      const data = await res.json();
      
      // 保存 token
      localStorage.setItem('token', data.token);
      console.log('Token saved to localStorage');
      
      // 跳转到个人中心页面
      history.push('/profile');
    } catch (error) {
      console.error('Login error:', error);
      alert('Login failed, please try again');
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        <div>
          <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
            Login to Room AI
          </h2>
          <p className="mt-2 text-center text-sm text-gray-600">
            Click the button below to start using
          </p>
        </div>
        <div className="mt-8 space-y-6">
          <button
            onClick={handleLogin}
            className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
          >
            Get started
          </button>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;